package com.mvc.framework.aop;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;

import com.mvc.framework.cache.CacheService;
import com.mvc.framework.model.CommonAuditableEntity;

public class CommonAuditableEntityUpdateInterceptor extends MethodCacheRemoveInterceptor {
	private static final Logger LOGGER = Logger.getLogger(CommonAuditableEntityUpdateInterceptor.class);
	private CacheService cacheService;
	/**
	 * Need flush method
	 */
	protected String[] CACHED_METHOD = new String[] { "getByObjectId"};

	public void afterReturning(Object returnValue, Method method, Object[] arguments, Object target) throws Throwable {
		String targetName = target.getClass().getName();
		if(arguments.length==1){
			Integer objectId = null;
			if(arguments[0] instanceof CommonAuditableEntity){
				objectId = ((CommonAuditableEntity)arguments[0]).getObjectId();
			}else if(arguments[0] instanceof CommonAuditableEntity){
				objectId = ((CommonAuditableEntity)arguments[0]).getObjectId();
			}
			if(objectId!=null){
				String cacheKey = KeyGenerator.getCacheKey(targetName, "getByObjectId", arguments);
				if("save".equals(method.getName())){
					cacheService.add(cacheKey, returnValue,null);
				}else{
					cacheService.delete(cacheKey);
				}
				if(LOGGER.isDebugEnabled()){
					LOGGER.debug("update key:" + cacheKey);
				}
			}
		}
	}

	public void setCacheService(CacheService cacheService) {
		this.cacheService = cacheService;
	}
}
